package org.goldenport.g3.platforms

import java.net.URL
import java.util.logging.Logger
import com.asamioffice.goldenport.io.UIO
import org.goldenport.g3._
import org.goldenport.g3.messages.http
import org.goldenport.g3.events.http._

/**
 * @since   Aug. 12, 2010
 * @version Oct.  6, 2010
 * @author  ASAMI, Tomoharu
 */
class AppEnginePlatform extends G3Platform {
  val logger = Logger.getLogger("g3") // XXX unify goldenport logging

  def httpGet(get: http.GET): G3Event = {
    new StringGETTED(get.uri, urlFetchString(new URL(get.uri)))
  }

  def httpPut(put: http.PUT): G3Event = {
    error("XXX httpPut")
  }

  def httpPost(post: http.POST): G3Event = {
    error("XXX httpPut")
  }

  def httpDelete(delete: http.DELETE): G3Event = {
    error("XXX httpPut")
  }

  def httpMkcol(mkcol: http.MKCOL): G3Event = {
    error("XXX httpPut")
  }

  def httpCopy(copy: http.COPY): G3Event = {
    error("XXX httpPut")
  }

  def httpMove(move: http.MOVE): G3Event = {
    error("XXX httpPut")
  }

  def urlFetchString(url: URL, encoding: String = "utf-8"): String = {
    var in = url.openStream()
    try {
      val bytes = UIO.stream2Bytes(in)
      new String(bytes, encoding)
    } finally {
      if (in != null) {
        in.close()
      }
    }
  }

  // SEVERE
  // WARNING
  // INFO
  // CONFIG
  // FINE
  // FINER
  // FINEST
  def logInfo(o: AnyRef, message: Any, data: Any = None) {
    val msg = make_message(o, "", message, data)
    logger.info(msg)
  }

  def logEnter(o: AnyRef, name: String, message: Any, data: Any = None) {
    val msg = make_message(o, name, message, data)
    logger.fine(msg)
  }

  def logLeave(o: AnyRef, name: String, message: Any, data: Any = None) {
    val msg = make_message(o, name, message, data)
    logger.fine(msg)
  }

  def logDebug(o: AnyRef, message: Any, data: Any = None) {
    val msg = make_message(o, "", message, data)
    logger.finer(msg)
  }

  def logInfoData(o: AnyRef, message: Any)(data: => Any) {
    val msg = make_message(o, "", message, data)
    logger.info(msg)
  }

  def logEnterData(o: AnyRef, name: String, message: Any)(data: => Any) {
    val msg = make_message(o, name, message, data)
    logger.fine(msg)
  }

  def logLeaveData(o: AnyRef, name: String, message: Any)(data: => Any) {
    val msg = make_message(o, name, message, data)
    logger.fine(msg)
  }

  def logDebugData(o: AnyRef, message: Any)(data: => Any) {
    val msg = make_message(o, "", message, data)
    logger.finer(msg)
  }
}
